package top.lyc829.myvideoplayer;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import top.lyc829.myvideoplayer.entity.EntityVideo;
import top.lyc829.myvideoplayer.tool.FileUtils;
import top.lyc829.myvideoplayer.ui.index.VideoAdapter;
import top.lyc829.myvideoplayer.ui.play.PlayActivity;

import static top.lyc829.myvideoplayer.BaseApplication.getContext;

public class MainActivity extends AppCompatActivity {


    private static final int CHOOSE_FILE = 1;
    String filePath;
    private RecyclerView recyclerView;//声明RecyclerView
    private VideoAdapter adapterDome;//声明适配器
    private Context context;
    private List<EntityVideo> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //打开app就检查读写权限
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {
            getVideoFromSDCard(this);
        }



        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        // 这里直接适配有一个bug：
        // 第一次打开应用获得授权后不显示视频，因为这是可能列表为空
        VideoAdapter videoAdapter = new VideoAdapter(list);//适配器对象
        recyclerView.setAdapter(videoAdapter);//设置适配器为上面的对象


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        switch (item.getItemId()){
            case R.id.menu_local:
                getVideoFromSDCard(getContext());
                VideoAdapter videoAdapter = new VideoAdapter(list);//适配器对象
                recyclerView.setAdapter(videoAdapter);//设置适配器为上面的对象

                String text = "扫描完成，一共" + String.valueOf(list.size()) + "个视频";
                Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
                break;
            case R.id.menu_open:
                openFileExplore();
                break;
            case R.id.menu_network:
                showDiaLog();
                break;
        }



        return true;
    }

    // 点击播放网络视频后显示带输入框的弹窗
    private void showDiaLog() {
        final EditText et = new EditText(this);
        new AlertDialog.Builder(this)
                .setTitle("请输入网址:")
                .setMessage("例如 http://example.com/video.mp4")
                //.setIcon(android.R.drawable.sym_def_app_icon)
                .setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //按下确定键后的事件
                        Toast.makeText(getApplicationContext(), et.getText().toString(),Toast.LENGTH_LONG).show();
                        navigateToPlay(et.getText().toString());
                    }
                }).setNegativeButton("取消",null).show();
    }

    private void navigateToPlay(String filePath) {
        Intent intent = new Intent(MainActivity.this, PlayActivity.class);
        intent.putExtra("filePath", filePath);
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }

        if (requestCode == CHOOSE_FILE) {

            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                filePath = FileUtils.getPath(MainActivity.this, uri);
                navigateToPlay(filePath);

            }
        }
    }

    /**
     * 从本地得到所有的视频地址
     */
    private void getVideoFromSDCard(Context context) {
        list.clear();
        String[] projection = new String[]{MediaStore.Video.Media.DATA, MediaStore.Video.Media
                .DURATION};
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, null,
                null, null);
        while (cursor.moveToNext()) {
            String path = cursor
                    .getString(cursor
                            .getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
            long duration = cursor
                    .getInt(cursor
                            .getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));

            EntityVideo video = new EntityVideo(path, duration);
            list.add(video);
        }
        cursor.close();
    }


    // 打开文件管理器
    private void openFileExplore() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("video/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, CHOOSE_FILE);
    }


    //检查权限的返回码处理
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //openFileExplore();
                getVideoFromSDCard(this);
            } else {
                //Toast.makeText(MainActivity.this, "未获得权限", Toast.LENGTH_SHORT).show();
                // TODO: 增加弹窗，提示用户授权才可用

                new AlertDialog.Builder(this)
                        .setTitle("提示")
                        .setMessage("允许读写文件才可用，请重试")
                        //.setIcon(android.R.drawable.sym_def_app_icon)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //按下确定键后的事件
                                finish();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                            }
                        }).show();

            }
        }
    }
}